//
//  scoreLayer.m
//  pipi
//
//  Created by zhao ys on 5/14/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "scoreLayer.h"
#import "startupLayer.h"
#import "GameCenter.h"


@implementation scoreLayer

+(CCScene *) sceneWithScore:(int)score
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	scoreLayer *layer = [scoreLayer node];
	[layer setScore:score];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init])) {
		CGSize size = [[CCDirector sharedDirector] winSize];
		_label = [CCLabelTTF labelWithString:@"" fontName:@"Marker Felt" fontSize:32];
        _label.position = ccp(size.width/2, 300);
        [self addChild:_label];
		
//		CCMenuItem * restart = [CCMenuItemImage itemFromNormalImage:@"restart.png" selectedImage:@"restart.png"
//															 target:self selector:@selector(OnRestart)];
		CCMenuItem * restart = [CCMenuItemFont itemFromString:@"[restart]" target:self selector:@selector(OnRestart:)];
		restart.position = ccp(100, 50);
#if _USE_GAMECENTER
		CCMenuItem * gamecenter = [CCMenuItemFont itemFromString:@"[GameCenter]" target:self selector:@selector(OnGameCenter:)];
		gamecenter.position = ccp(300, 50);	
#else
		CCMenuItem * gamecenter = nil;
#endif
		CCMenu * menu = [CCMenu menuWithItems:restart, gamecenter, nil];
		menu.position = ccp(0,0);
		//[menu alignItemsVertically];
		[self addChild:menu];
	}
	return self;
}

-(void) setScore:(int)score {
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	int maxScore = [defaults integerForKey:@"MaxScore"];	
	if (score > maxScore ) {
		maxScore = score;
		[defaults setInteger:maxScore forKey:@"MaxScore"];
#ifdef _USE_GAMECENTER		
		[[GameCenter sharedGameCenter] reportScore:score];
#endif
	}
	
	if (score > 0 ) {
		[_label setString:[NSString stringWithFormat:@"score: %d / %d", score, maxScore]];
	} else {
		[_label setString:[NSString stringWithFormat:@"max score: %d", maxScore]];
	}
}

-(void) OnRestart:(id)sender {
	[[CCDirector sharedDirector] replaceScene:[startupLayer scene]];
	[[CCDirector sharedDirector] resume];
}

-(void) OnGameCenter:(id)sender {
	[[GameCenter sharedGameCenter] enterLeaderboard:@"xx" withView:[[CCDirector sharedDirector] openGLView]];
}

@end
